package com.minisoft.customer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.minisoft.entity.OpportunityDetailsXcxVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * @author JueSu
 * @description: TODO
 * @date 2023/7/4 17:09
 */
@Slf4j
public class FlushFilledRate {

//    public static String DB_CENTER = "center-pro";
//    public static String DB_CENTER_READ = "center-pro-read";

    public static String DB_CENTER = "center-dev";
//    public static String DB_CENTER_READ = "center-dev";
    private static long beginTime = System.currentTimeMillis();;
    private static AtomicLong totalNum = new AtomicLong(0);
    public static String URL = "http://user-service-pre.paas.huafagroup.com/saleMain/customerListXcx";
    public static void main(String[] args) throws SQLException {
        ExecutorService service = ThreadUtil.newExecutor(6);
        //获取案场
        List<Entity> saleTeamIds = Db.use(DB_CENTER).query("select st.sale_team_id  from sale_team st where st.deleted = 0");
        for (Entity item : saleTeamIds) {
//            service.execute(new FlushSaleTeamData(item.getStr("sale_team_id")));
        }
//        service.execute(new FlushSaleTeamData("1000002"));
        service.execute(new FlushSaleTeamData("1000114"));
//        service.execute(new FlushSaleTeamData("1000015"));
//        service.execute(new FlushSaleTeamData("1000118"));
        //1000-全局总耗时：331s，全局总人数：79720
        //500- 全局总耗时：518s，全局总人数：79720
        //1500-全局总耗时：420s，全局总人数：79720
    }

    static class FlushSaleTeamData implements Runnable{

        private String saleTeamId;

        public FlushSaleTeamData(String saleTeamId){
            this.saleTeamId = saleTeamId;
        }
        @SneakyThrows
        @Override
        public void run() {
            Page page = new Page();
            page.setPageSize(1000);
            int pageNum = 0;//从第0页开始
            int total = 0;
            PageResult<Entity> pageResult = getPageResult(pageNum,page);
            long startTime = System.currentTimeMillis();
            while (!pageResult.isEmpty()) {
                List<Object[]> params = pageResult.stream().map(item -> {
                    OpportunityDetailsXcxVo user = item.toBean(OpportunityDetailsXcxVo.class);
                    return new Object[]{user.getCompletePercent(),user.getId()};
                }).collect(Collectors.toList());
                total+=pageResult.size();
                Db.use(DB_CENTER).executeBatch("update customer_opportunity set filled_rate = ? where id = ?",params);
                log.info("案场{}更新第{}页客户，已更新总量：{}",saleTeamId,pageNum,total);
                pageNum++;
                pageResult = getPageResult(pageNum,page);
            }
            long endTime = System.currentTimeMillis();
            int second = (int) (endTime-startTime)/1000;
            log.info("案场：{}，耗时：{}s,全局总耗时：{}s，全局总人数：{}",saleTeamId,second,(endTime-beginTime)/1000,totalNum.addAndGet(total));
        }

        private PageResult<Entity> getPageResult(int pageNum, Page page) throws SQLException {
            page.setPageNumber(0);//因为只返回未更新的，所以只拿第0页就好
            PageResult<Entity> pageResult = Db.use(DB_CENTER).page("select ifnull(a.address,co.address) address,\n" +
                    "               ifnull(cc.cert_type_name,co.id_card_type) id_card_type,\n" +
                    "               ifnull(cc.cert_number,co.id_card_no) id_card_no,\n" +
                    "               co.id, co.customer_opportunity_id, co.customer_id, co.sale_team_id, co.customer_name, co.gender, co.cp_user_create_time, co.sale_main_name, co.sale_main_id, co.sale_open_id, co.agent_id, co.agent_name, co.agent_states, co.contact_type_id, co.contact_type_name, co.chance, co.visit_first_date, co.visit_last_date, co.target_unit_price, co.target_total_price_name, co.work_area, co.app_id, co.cp_user_id, co.work_area_name, co.target_objective_name, co.target_acreage_name, co.target_house_type, co.description, co.usersrc, co.customer_typd_name, co.channel_way_name, co.visit_channel_id, co.visit_channel_name, co.visit_code, co.opportunity_state, co.profession_id, co.family_member_id, co.living_num, co.vehicle, co.car_park_id, co.car_park_name, co.car_brand_id, co.activities, co.buyfactor, co.liveplate, co.is_limited_buy, co.is_limited_loan, co.userrank, co.notbuyreason, co.photo, co.is_pool, co.share_open_id, co.share_user_key, co.yxuserid, co.distribute_time, co.propcondition, co.age, co.is_importance, co.user_from, co.call_time, co.org_id, co.is_new_bind, co.visit_type, co.code, co.sys_id, co.deleted, co.create_id, co.create_time, co.create_app, co.update_id, co.update_time, co.update_app, co.deal_protected_period, co.sale_team_name, co.sales_resistance_id, co.customer_label_id, co.customer_label_name, co.work_area_id, co.other_visit_channel_id, co.other_visit_channel_name, co.target_house_type_name, co.target_house_format, co.target_house_format_name, co.target_acreage, co.target_objective, co.target_standard_name, co.target_standard, co.target_total_price, co.target_unit_price_name, co.to_person_sum_name, co.to_person_sum, co.family_income_name, co.family_income_id, co.family_member_name, co.vehicle_name, co.profession_name, co.car_brand_name, co.trade_name, co.trade_id, co.living_num_name, co.education_name, co.education_id, co.age_stage_name, co.age_stage, co.limited_buy_way_text, co.limited_buy_way_name, co.limited_buy_way_id, co.limited_loan_way_text, co.limited_loan_way_name, co.limited_loan_way_id, co.focus_id, co.focus_name, co.is_important_name, co.channel_way_id, co.`grouping`, co.chance_name, co.chance_id, co.channel_id, co.channel_name, co.problem_customer_reason, co.visiting_area_name, co.visiting_area, co.is_new_potential, co.is_new_potential_name, co.nm_flag, co.customer_info_id, co.myxssrs, co.sales_resistance_name, co.follow_last_date, co.org_cus_visit_date, co.org_cus_visit_extend_date,\n" +
                    "               cc.cert_type_id id_card_type_id,\n" +
                    "               a2.address address1,cm.mobile mobile1,cm2.mobile mobile2,m.mobile,\n" +
                    "               c.nation_id ,c.nation_name,c.customer_type_id,c.customer_type_name,c.registered_address,c.business_license,\n" +
                    "               c.organization_code, c.legal_representative, c.is_taxpayers, c.taxpayer_identification_number, c.business_scope, c.bank_account, c.bank\n" +
                    "        from customer_opportunity co\n" +
                    "             left join customer c on c.customer_id = co.customer_id\n" +
                    "             left join customer_mobile m on m.customer_opportunity_id = co.customer_opportunity_id and m.deleted=0 and m.sort = 0\n" +
                    "             left join address a on a.customer_opportunity_id = co.customer_opportunity_id and a.sort = 4 and a.deleted = 0\n" +
                    "             left join address a2 on a2.customer_opportunity_id = co.customer_opportunity_id and a2.sort = 1 and a2.deleted = 0\n" +
                    "             left join customer_mobile cm on cm.customer_opportunity_id = co.customer_opportunity_id and cm.sort = 1 and cm.deleted = 0\n" +
                    "             left join customer_mobile cm2 on cm2.customer_opportunity_id = co.customer_opportunity_id and cm2.sort = 2 and cm2.deleted = 0\n" +
                    "             left join customer_cert cc on cc.customer_opportunity_id = co.customer_opportunity_id and cc.deleted = 0\n" +
                    "        where co.deleted = 0 and co.sale_team_id = ? and co.filled_rate = 0 ", page,saleTeamId);
            return pageResult;
        }

    }

    static class FlushSaleTeamData2 implements Runnable{

        private String saleTeamId;

        public FlushSaleTeamData2(String saleTeamId){
            this.saleTeamId = saleTeamId;
        }
        @SneakyThrows
        @Override
        public void run() {
            //获取置业顾问列表
            List<Entity> userList = Db.use(DB_CENTER).query("select sc.user_key from sale_consultant sc where sc.position_id in ('1063001','1063006','1063007') and sc.sale_team_id = ?", saleTeamId);
            for (Entity entity : userList) {
                JSONObject jsonObject = new JSONObject();
                int pageNo = 1;
                String loginUserKey = entity.getStr("user_key");
                JSONArray users = getUsers(loginUserKey, jsonObject, pageNo);
                while (CollUtil.isNotEmpty(users)) {
                    List<Object[]> params = users.stream().map(item -> {
                        JSONObject user = (JSONObject) item;
                        return new Object[]{user.getInt("completePercent"),user.get("id")};
                    }).collect(Collectors.toList());
                    Db.use(DB_CENTER).executeBatch("update customer_opportunity set filled_rate = ? where id = ?",params);
                    Console.log("案场{}更新{}第{}页客户量：{}",saleTeamId,loginUserKey,pageNo,users.size());
                    pageNo++;
                    users = getUsers(loginUserKey, jsonObject, pageNo);
                }
            }
        }

        private JSONArray getUsers(String loginUserKey, JSONObject jsonObject, int pageNo) {
            jsonObject.set("loginUserKey", loginUserKey).set("saleTeamId",saleTeamId).set("pageNo", pageNo).set("pageSize",300);
            JSONObject result = JSONUtil.parseObj(HttpUtil.post(URL, jsonObject.toString()));
            JSONArray users = result.getJSONObject("data").getJSONArray("records");
            return users;
        }
    }


}
